// 全局变量
let floatingH = null;
let extractorModal = null;
let isExtensionEnabled = false;
let selectorHistory = [];

// 创建悬浮H字母
function createFloatingH() {
    if (floatingH) return;
    
    floatingH = document.createElement('div');
    floatingH.id = 'html-extractor-floating-h';
    floatingH.innerHTML = 'H';
    floatingH.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 50px;
        height: 50px;
        background-color: #3498db;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        font-weight: bold;
        cursor: pointer;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        user-select: none;
        transition: all 0.3s ease;
    `;
    
    // 添加拖拽功能
    let isDragging = false;
    let currentX = 0;
    let currentY = 0;
    let initialX = 0;
    let initialY = 0;
    let xOffset = 0;
    let yOffset = 0;
    
    floatingH.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', dragEnd);
    
    floatingH.addEventListener('click', function(e) {
        if (!isDragging) {
            showExtractorModal();
        }
    });
    
    floatingH.addEventListener('mouseenter', function() {
        this.style.transform = 'scale(1.1)';
        this.style.backgroundColor = '#2980b9';
    });
    
    floatingH.addEventListener('mouseleave', function() {
        this.style.transform = 'scale(1)';
        this.style.backgroundColor = '#3498db';
    });
    
    function dragStart(e) {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
        
        if (e.target === floatingH) {
            isDragging = true;
        }
    }
    
    function drag(e) {
        if (isDragging) {
            e.preventDefault();
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
            
            xOffset = currentX;
            yOffset = currentY;
            
            floatingH.style.transform = `translate(${currentX}px, ${currentY}px) scale(1.1)`;
        }
    }
    
    function dragEnd(e) {
        initialX = currentX;
        initialY = currentY;
        isDragging = false;
        
        floatingH.style.transform = `translate(${currentX}px, ${currentY}px) scale(1)`;
    }
    
    document.body.appendChild(floatingH);
}

// 移除悬浮H字母
function removeFloatingH() {
    if (floatingH) {
        floatingH.remove();
        floatingH = null;
    }
}

// 创建提取器模态框
function createExtractorModal() {
    if (extractorModal) return;
    
    extractorModal = document.createElement('div');
    extractorModal.id = 'html-extractor-modal';
    extractorModal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        z-index: 10001;
        display: none;
        align-items: center;
        justify-content: center;
    `;
    
    const modalContent = document.createElement('div');
    modalContent.id = 'modal-content';
    modalContent.style.cssText = `
        background: white;
        border-radius: 8px;
        padding: 0;
        width: 800px;
        height: 600px;
        position: relative;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        display: flex;
        flex-direction: column;
        min-width: 400px;
        min-height: 300px;
        max-width: 95vw;
        max-height: 95vh;
    `;
    
    modalContent.innerHTML = `
        <div id="modal-titlebar" style="
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding: 15px 20px; 
            border-bottom: 1px solid #ddd; 
            background: #f8f9fa;
            border-radius: 8px 8px 0 0;
            cursor: move;
            user-select: none;
        ">
            <h2 style="margin: 0; color: #2c3e50; font-size: 18px;">HTML文本提取器</h2>
            <button id="close-modal" style="
                background: #e74c3c; 
                color: white; 
                border: none; 
                padding: 8px 12px; 
                border-radius: 4px; 
                cursor: pointer; 
                font-size: 16px;
                font-weight: bold;
            ">×</button>
        </div>
        <div id="modal-body" style="
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        ">
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #2c3e50;">jQuery选择器（多个用 | 分隔）：</label>
                <div style="position: relative;">
                    <input type="text" id="modal-selector-input" placeholder="例如：p, .classname, #id" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    <div id="modal-selector-history" style="
                        position: absolute;
                        top: 100%;
                        left: 0;
                        right: 0;
                        background: white;
                        border: 1px solid #ddd;
                        border-top: none;
                        border-radius: 0 0 4px 4px;
                        max-height: 200px;
                        overflow-y: auto;
                        z-index: 1000;
                        display: none;
                        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                    "></div>
                </div>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #2c3e50;">属性名（可选，多个用 | 分隔）：</label>
                <input type="text" id="modal-attribute-input" placeholder="例如：src, href, title, data-id" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                <div style="font-size: 12px; color: #666; margin-top: 5px; font-style: italic;">留空则提取文本内容，填写属性名则提取属性值</div>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: flex; align-items: center; gap: 8px;">
                    <input type="checkbox" id="modal-extract-both" checked>
                    <span>同时提取属性和文本</span>
                </label>
                <div style="font-size: 12px; color: #666; margin-top: 5px; font-style: italic;">勾选后，每个元素会同时提取属性值和文本内容</div>
            </div>
            <div style="margin-bottom: 15px;">
                <button id="modal-get-html-btn" style="background-color: #3498db; color: white; border: none; padding: 10px 15px; font-size: 14px; border-radius: 4px; cursor: pointer; margin-right: 10px;">获取当前页面HTML</button>
                <button id="modal-load-example-btn" style="background-color: #f39c12; color: white; border: none; padding: 10px 15px; font-size: 14px; border-radius: 4px; cursor: pointer; margin-right: 10px;">加载示例</button>
                <button id="modal-extract-btn" style="background-color: #27ae60; color: white; border: none; padding: 10px 15px; font-size: 14px; border-radius: 4px; cursor: pointer; margin-right: 10px;">提取文本</button>
                <button id="modal-save-config-btn" style="background-color: #9b59b6; color: white; border: none; padding: 10px 15px; font-size: 14px; border-radius: 4px; cursor: pointer; opacity: 0.5;" disabled>保存配置</button>
            </div>
            <div style="margin-bottom: 15px; flex: 1; display: flex; flex-direction: column;">
                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #2c3e50;">HTML源代码：</label>
                <textarea id="modal-html-input" placeholder="点击上方按钮获取当前页面HTML..." style="width: 100%; flex: 1; min-height: 120px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box; font-family: monospace; resize: none;"></textarea>
            </div>
            <div style="margin-bottom: 15px; flex: 1; display: flex; flex-direction: column;">
                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #2c3e50;">提取结果：</label>
                <textarea id="modal-result" readonly placeholder="提取结果将显示在这里..." style="width: 100%; flex: 1; min-height: 120px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; box-sizing: border-box; font-family: monospace; resize: none;"></textarea>
            </div>
            <div id="modal-error-message" style="color: #e74c3c; padding: 8px; background-color: #fadbd8; border-radius: 4px; margin-top: 10px; display: none;"></div>
            <div id="modal-success-message" style="color: #27ae60; padding: 8px; background-color: #d5f4e6; border-radius: 4px; margin-top: 10px; display: none;"></div>
        </div>
        <div id="resize-handles" style="position: absolute; bottom: 0; right: 0; width: 20px; height: 20px; cursor: se-resize; background: linear-gradient(-45deg, transparent 0%, transparent 30%, #ccc 30%, #ccc 40%, transparent 40%, transparent 60%, #ccc 60%, #ccc 70%, transparent 70%);"></div>
    `;
    
    extractorModal.appendChild(modalContent);
    document.body.appendChild(extractorModal);
    
    // 绑定事件
    document.getElementById('close-modal').addEventListener('click', hideExtractorModal);
    document.getElementById('modal-get-html-btn').addEventListener('click', getCurrentPageHTML);
    document.getElementById('modal-load-example-btn').addEventListener('click', loadModalExample);
    document.getElementById('modal-extract-btn').addEventListener('click', extractText);
    document.getElementById('modal-save-config-btn').addEventListener('click', saveCurrentPageConfig);
    
    // 添加拖拽功能
    setupModalDragging();
    
    // 添加缩放功能
    setupModalResizing();
    
    // 加载保存的位置和大小
    loadModalPositionAndSize();
    
    // 设置选择器历史记录功能
    setupSelectorHistory();
    
    // 监听选择器输入变化，禁用保存按钮
    const selectorInput = document.getElementById('modal-selector-input');
    if (selectorInput) {
        selectorInput.addEventListener('input', function() {
            disableSaveConfigButton();
        });
    }
}

// 设置模态框拖拽功能
function setupModalDragging() {
    const titleBar = document.getElementById('modal-titlebar');
    const modalContent = document.getElementById('modal-content');
    let isDragging = false;
    let currentX = 0;
    let currentY = 0;
    let initialX = 0;
    let initialY = 0;
    let xOffset = 0;
    let yOffset = 0;

    titleBar.addEventListener('mousedown', dragStart);
    document.addEventListener('mousemove', drag);
    document.addEventListener('mouseup', dragEnd);

    function dragStart(e) {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;

        if (e.target === titleBar || titleBar.contains(e.target)) {
            isDragging = true;
            titleBar.style.cursor = 'grabbing';
        }
    }

    function drag(e) {
        if (isDragging) {
            e.preventDefault();
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;

            xOffset = currentX;
            yOffset = currentY;

            modalContent.style.transform = `translate(${currentX}px, ${currentY}px)`;
        }
    }

    function dragEnd(e) {
        initialX = currentX;
        initialY = currentY;
        isDragging = false;
        titleBar.style.cursor = 'move';
        
        // 保存位置
        saveModalPositionAndSize();
    }
}

// 设置模态框缩放功能
function setupModalResizing() {
    const modalContent = document.getElementById('modal-content');
    const resizeHandle = document.getElementById('resize-handles');
    let isResizing = false;
    let startX = 0;
    let startY = 0;
    let startWidth = 0;
    let startHeight = 0;

    resizeHandle.addEventListener('mousedown', resizeStart);
    document.addEventListener('mousemove', resize);
    document.addEventListener('mouseup', resizeEnd);

    function resizeStart(e) {
        isResizing = true;
        startX = e.clientX;
        startY = e.clientY;
        startWidth = parseInt(document.defaultView.getComputedStyle(modalContent).width, 10);
        startHeight = parseInt(document.defaultView.getComputedStyle(modalContent).height, 10);
        e.preventDefault();
    }

    function resize(e) {
        if (isResizing) {
            const newWidth = startWidth + e.clientX - startX;
            const newHeight = startHeight + e.clientY - startY;
            
            // 设置最小和最大尺寸
            const minWidth = 400;
            const minHeight = 300;
            const maxWidth = window.innerWidth * 0.95;
            const maxHeight = window.innerHeight * 0.95;
            
            const finalWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));
            const finalHeight = Math.max(minHeight, Math.min(maxHeight, newHeight));
            
            modalContent.style.width = finalWidth + 'px';
            modalContent.style.height = finalHeight + 'px';
        }
    }

    function resizeEnd(e) {
        isResizing = false;
        // 保存位置和大小
        saveModalPositionAndSize();
    }
}

// 保存模态框位置和大小
function saveModalPositionAndSize() {
    const modalContent = document.getElementById('modal-content');
    if (modalContent) {
        const rect = modalContent.getBoundingClientRect();
        const position = {
            x: rect.left,
            y: rect.top,
            width: rect.width,
            height: rect.height
        };
        
        chrome.storage.local.set({modalPosition: position});
    }
}

// 加载模态框位置和大小
function loadModalPositionAndSize() {
    chrome.storage.local.get(['modalPosition'], function(data) {
        if (data.modalPosition) {
            const modalContent = document.getElementById('modal-content');
            if (modalContent) {
                const pos = data.modalPosition;
                // 确保位置在屏幕范围内
                const maxX = window.innerWidth - pos.width;
                const maxY = window.innerHeight - pos.height;
                
                const finalX = Math.max(0, Math.min(maxX, pos.x));
                const finalY = Math.max(0, Math.min(maxY, pos.y));
                
                modalContent.style.left = finalX + 'px';
                modalContent.style.top = finalY + 'px';
                modalContent.style.width = pos.width + 'px';
                modalContent.style.height = pos.height + 'px';
                modalContent.style.position = 'fixed';
                modalContent.style.transform = 'none';
            }
        }
    });
}

// 显示提取器模态框
function showExtractorModal() {
    if (!extractorModal) {
        createExtractorModal();
    }
    
    // 加载保存的设置和自动填充配置
    chrome.storage.local.get(['lastSelector', 'lastAttribute', 'extractBoth', 'urlConfigs'], function(data) {
        let selector = data.lastSelector || '';
        let attribute = data.lastAttribute || '';
        let extractBoth = data.extractBoth || false;
        
        // 尝试自动填充配置
        const currentUrl = window.location.href;
        const config = findMatchingConfigForModal(currentUrl, data.urlConfigs || []);
        
        if (config) {
            selector = config.selector;
            attribute = config.attribute;
            extractBoth = config.extractBoth;
        }
        
        document.getElementById('modal-selector-input').value = selector;
        document.getElementById('modal-attribute-input').value = attribute;
        document.getElementById('modal-extract-both').checked = extractBoth;
    });
    
    extractorModal.style.display = 'flex';
    getCurrentPageHTML();
}

// 隐藏提取器模态框
function hideExtractorModal() {
    if (extractorModal) {
        extractorModal.style.display = 'none';
    }
}

// 获取当前页面HTML
function getCurrentPageHTML() {
    showModalMessage('正在获取页面HTML...', 'success');
    
    try {
        const html = document.documentElement.outerHTML;
        document.getElementById('modal-html-input').value = html;
        showModalMessage('成功获取页面HTML', 'success');
    } catch (error) {
        showModalError('获取HTML出错: ' + error.message);
    }
}

// 提取文本
function extractText() {
    const htmlContent = document.getElementById('modal-html-input').value;
    const selector = document.getElementById('modal-selector-input').value;
    const attribute = document.getElementById('modal-attribute-input').value;
    const extractBoth = document.getElementById('modal-extract-both').checked;
    
    // 保存设置
    chrome.storage.local.set({
        lastSelector: selector,
        lastAttribute: attribute,
        extractBoth: extractBoth
    });
    
    // 保存选择器到历史记录
    saveSelectorHistory(selector);
    
    if (!htmlContent.trim()) {
        showModalError('请先获取HTML内容');
        return;
    }
    
    if (!selector.trim()) {
        showModalError('请输入选择器');
        return;
    }
    
    try {
        // 创建临时DOM元素来解析HTML
        const tempContainer = document.createElement('div');
        tempContainer.innerHTML = htmlContent;
        
        // 分割多个选择器
        const selectors = selector.split('|').map(s => s.trim()).filter(s => s);
        
        // 分割多个属性（如果提供了）
        const attributes = attribute ? attribute.split('|').map(a => a.trim()).filter(a => a) : [];
        
        // 确保选择器和属性数量匹配（除非是同时提取模式）
        if (attributes.length > 0 && attributes.length !== selectors.length && !extractBoth) {
            showModalError('选择器和属性数量必须匹配');
            return;
        }
        
        let results = [];
        
        if (extractBoth) {
            // 同时提取属性和文本模式
            results = selectors.map((sel, index) => {
                const elements = tempContainer.querySelectorAll(sel);
                return Array.from(elements).map(element => {
                    const attrValue = attributes[index] ? (element.getAttribute(attributes[index]) || '') : '';
                    const textValue = element.textContent.trim();
                    return `${attrValue}\t${textValue}`;
                });
            });
        } else {
            // 原有模式：要么提取属性，要么提取文本
            results = selectors.map((sel, index) => {
                const elements = tempContainer.querySelectorAll(sel);
                return Array.from(elements).map(element => {
                    if (attributes.length > 0 && attributes[index]) {
                        // 提取属性值
                        return element.getAttribute(attributes[index]) || '';
                    } else {
                        // 提取文本内容
                        return element.textContent.trim();
                    }
                });
            });
        }
        
        // 检查是否有结果
        if (results.some(arr => arr.length === 0)) {
            showModalError('某些选择器没有找到匹配的元素');
            return;
        }
        
        // 提取文本内容
        let resultText = '';
        const rowCount = Math.max(...results.map(arr => arr.length));
        
        for (let i = 0; i < rowCount; i++) {
            let rowText = '';
            selectors.forEach((sel, colIndex) => {
                const value = results[colIndex][i] || '';
                rowText += value + '\t';
            });
            resultText += rowText.trim() + '\n';
        }
        
        document.getElementById('modal-result').value = resultText.trim();
        hideModalMessage('error');
        let extractType = '数据';
        if (extractBoth) {
            extractType = '属性和文本数据';
        } else if (attributes.length > 0) {
            extractType = '属性数据';
        } else {
            extractType = '文本数据';
        }
        showModalMessage(`成功提取 ${rowCount} 行${extractType}`, 'success');
        
        // 启用保存配置按钮
        enableSaveConfigButton();
        
    } catch (error) {
        showModalError('提取过程中发生错误: ' + error.message);
    }
}

// 显示模态框消息
function showModalMessage(message, type) {
    const errorEl = document.getElementById('modal-error-message');
    const successEl = document.getElementById('modal-success-message');
    
    if (type === 'error') {
        errorEl.textContent = message;
        errorEl.style.display = 'block';
        successEl.style.display = 'none';
    } else {
        successEl.textContent = message;
        successEl.style.display = 'block';
        errorEl.style.display = 'none';
        // 3秒后自动隐藏成功消息
        setTimeout(() => {
            successEl.style.display = 'none';
        }, 3000);
    }
}

function showModalError(message) {
    showModalMessage(message, 'error');
}

function hideModalMessage(type) {
    if (type === 'error') {
        document.getElementById('modal-error-message').style.display = 'none';
    } else {
        document.getElementById('modal-success-message').style.display = 'none';
    }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("收到消息:", request);
    
    if (request.action === "getHTML") {
        try {
            // 获取页面的完整HTML
            const html = document.documentElement.outerHTML;
            console.log("成功获取HTML，长度:", html.length);
            
            // 发送响应
            sendResponse({
                success: true,
                html: html,
                url: window.location.href,
                title: document.title
            });
        } catch (error) {
            console.error("获取HTML出错:", error);
            sendResponse({
                success: false,
                error: error.message
            });
        }
    } else if (request.action === "toggleExtension") {
        isExtensionEnabled = request.enabled;
        if (isExtensionEnabled) {
            createFloatingH();
        } else {
            removeFloatingH();
            hideExtractorModal();
        }
    }
    
    // 保持消息通道开放
    return true;
});

// 设置选择器历史记录功能
function setupSelectorHistory() {
    const selectorInput = document.getElementById('modal-selector-input');
    const historyDiv = document.getElementById('modal-selector-history');
    
    if (!selectorInput || !historyDiv) return;
    
    // 加载历史记录
    loadSelectorHistory();
    
    // 输入框获得焦点时显示历史记录
    selectorInput.addEventListener('focus', function() {
        showSelectorHistory();
    });
    
    // 输入框失去焦点时隐藏历史记录（延迟一点时间，让点击历史项有时间执行）
    selectorInput.addEventListener('blur', function() {
        setTimeout(() => {
            hideSelectorHistory();
        }, 200);
    });
    
    // 输入时过滤历史记录
    selectorInput.addEventListener('input', function() {
        filterSelectorHistory(this.value);
    });
    
    // 键盘事件处理
    selectorInput.addEventListener('keydown', function(e) {
        const historyItems = historyDiv.querySelectorAll('.history-item');
        const activeItem = historyDiv.querySelector('.history-item.active');
        
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (activeItem) {
                activeItem.classList.remove('active');
                const nextItem = activeItem.nextElementSibling;
                if (nextItem) {
                    nextItem.classList.add('active');
                } else if (historyItems.length > 0) {
                    historyItems[0].classList.add('active');
                }
            } else if (historyItems.length > 0) {
                historyItems[0].classList.add('active');
            }
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (activeItem) {
                activeItem.classList.remove('active');
                const prevItem = activeItem.previousElementSibling;
                if (prevItem) {
                    prevItem.classList.add('active');
                } else if (historyItems.length > 0) {
                    historyItems[historyItems.length - 1].classList.add('active');
                }
            } else if (historyItems.length > 0) {
                historyItems[historyItems.length - 1].classList.add('active');
            }
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (activeItem) {
                selectHistoryItem(activeItem);
            }
        } else if (e.key === 'Escape') {
            hideSelectorHistory();
        }
    });
}

// 加载选择器历史记录
function loadSelectorHistory() {
    chrome.storage.local.get(['selectorHistory'], function(data) {
        selectorHistory = data.selectorHistory || [];
        updateSelectorHistoryDisplay();
    });
}

// 保存选择器历史记录
function saveSelectorHistory(selector) {
    if (!selector || !selector.trim()) return;
    
    // 移除重复项
    selectorHistory = selectorHistory.filter(item => item !== selector);
    
    // 添加到开头
    selectorHistory.unshift(selector);
    
    // 限制最多10条记录
    if (selectorHistory.length > 10) {
        selectorHistory = selectorHistory.slice(0, 10);
    }
    
    // 保存到存储
    chrome.storage.local.set({selectorHistory: selectorHistory});
    
    // 更新显示
    updateSelectorHistoryDisplay();
}

// 更新历史记录显示
function updateSelectorHistoryDisplay() {
    const historyDiv = document.getElementById('modal-selector-history');
    if (!historyDiv) return;
    
    if (selectorHistory.length === 0) {
        historyDiv.innerHTML = '<div style="padding: 8px; color: #666; text-align: center;">暂无历史记录</div>';
        return;
    }
    
    // 清空历史记录容器
    historyDiv.innerHTML = '';
    
    // 使用DOM创建元素，避免模板字符串中的特殊字符问题
    selectorHistory.forEach((item, index) => {
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        historyItem.setAttribute('data-selector', item); // 直接设置属性，浏览器会自动转义
        historyItem.style.cssText = `
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
            transition: background-color 0.2s;
        `;
        
        // 添加鼠标悬停效果
        historyItem.addEventListener('mouseenter', function() {
            this.style.backgroundColor = '#f5f5f5';
        });
        historyItem.addEventListener('mouseleave', function() {
            this.style.backgroundColor = 'white';
        });
        
        // 创建内容
        const titleDiv = document.createElement('div');
        titleDiv.style.cssText = 'font-weight: 500; color: #2c3e50;';
        titleDiv.textContent = item; // 使用textContent安全设置文本
        
        const hintDiv = document.createElement('div');
        hintDiv.style.cssText = 'font-size: 12px; color: #666; margin-top: 2px;';
        hintDiv.textContent = '点击选择';
        
        historyItem.appendChild(titleDiv);
        historyItem.appendChild(hintDiv);
        historyDiv.appendChild(historyItem);
    });
    
    // 添加点击事件
    historyDiv.querySelectorAll('.history-item').forEach(item => {
        item.addEventListener('click', function() {
            selectHistoryItem(this);
        });
    });
}

// 显示历史记录
function showSelectorHistory() {
    const historyDiv = document.getElementById('modal-selector-history');
    if (historyDiv && selectorHistory.length > 0) {
        historyDiv.style.display = 'block';
    }
}

// 隐藏历史记录
function hideSelectorHistory() {
    const historyDiv = document.getElementById('modal-selector-history');
    if (historyDiv) {
        historyDiv.style.display = 'none';
        // 清除活动状态
        const activeItem = historyDiv.querySelector('.history-item.active');
        if (activeItem) {
            activeItem.classList.remove('active');
        }
    }
}

// 过滤历史记录
function filterSelectorHistory(query) {
    const historyDiv = document.getElementById('modal-selector-history');
    if (!historyDiv) return;
    
    const items = historyDiv.querySelectorAll('.history-item');
    const lowerQuery = query.toLowerCase();
    
    items.forEach(item => {
        const selector = item.getAttribute('data-selector').toLowerCase();
        if (selector.includes(lowerQuery)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
    
    // 显示或隐藏历史记录容器
    const visibleItems = Array.from(items).filter(item => item.style.display !== 'none');
    if (visibleItems.length > 0) {
        historyDiv.style.display = 'block';
    } else {
        historyDiv.style.display = 'none';
    }
}


// 选择历史记录项
function selectHistoryItem(item) {
    const selector = item.getAttribute('data-selector');
    const selectorInput = document.getElementById('modal-selector-input');
    
    if (selectorInput) {
        selectorInput.value = selector;
        selectorInput.focus();
        hideSelectorHistory();
    }
}

// 加载模态框示例
function loadModalExample() {
    // 示例HTML内容
    const exampleHTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品展示示例</title>
    <style>
        .product-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 20px;
            max-width: 300px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
        }
        .product-title {
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
            color: #333;
        }
        .product-link {
            color: #007bff;
            text-decoration: none;
            font-weight: 500;
        }
        .product-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/4CAF50/FFFFFF?text=示例商品图片" 
             alt="商品图片" 
             class="product-image">
        <h3 class="product-title">优质商品标题</h3>
        <a href="https://example.com/product/123" 
           class="product-link" 
           target="_blank">
            查看商品详情
        </a>
    </div>
    
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/2196F3/FFFFFF?text=另一个商品" 
             alt="另一个商品图片" 
             class="product-image">
        <h3 class="product-title">另一个商品标题</h3>
        <a href="https://example.com/product/456" 
           class="product-link" 
           target="_blank">
            立即购买
        </a>
    </div>
</body>
</html>`;

    // 设置示例数据
    document.getElementById('modal-selector-input').value = 'a | img';
    document.getElementById('modal-attribute-input').value = 'href | src';
    document.getElementById('modal-extract-both').checked = true;
    document.getElementById('modal-html-input').value = exampleHTML;
    
    // 显示成功消息
    showModalMessage('已加载示例数据！现在可以点击"提取文本"按钮查看效果', 'success');
    
    // 保存示例选择器到历史记录
    saveSelectorHistory('a | img');
}

// 加载popup示例
function loadPopupExample() {
    // 示例HTML内容
    const exampleHTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品展示示例</title>
    <style>
        .product-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 20px;
            max-width: 300px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
        }
        .product-title {
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
            color: #333;
        }
        .product-link {
            color: #007bff;
            text-decoration: none;
            font-weight: 500;
        }
        .product-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/4CAF50/FFFFFF?text=示例商品图片" 
             alt="商品图片" 
             class="product-image">
        <h3 class="product-title">优质商品标题</h3>
        <a href="https://example.com/product/123" 
           class="product-link" 
           target="_blank">
            查看商品详情
        </a>
    </div>
    
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/2196F3/FFFFFF?text=另一个商品" 
             alt="另一个商品图片" 
             class="product-image">
        <h3 class="product-title">另一个商品标题</h3>
        <a href="https://example.com/product/456" 
           class="product-link" 
           target="_blank">
            立即购买
        </a>
    </div>
</body>
</html>`;

    // 设置示例数据
    $('#selector-input').val('a | img');
    $('#attribute-input').val('href | src');
    $('#extract-both').prop('checked', true);
    $('#html-input').val(exampleHTML);
    
    // 显示成功消息
    showMessage('已加载示例数据！现在可以点击"提取文本"按钮查看效果', 'success');
    
    // 保存示例选择器到历史记录
    savePopupSelectorHistory('a | img');
}

// 查找匹配的配置（用于模态框）
function findMatchingConfigForModal(url, urlConfigs) {
    // 1. 精确匹配
    let config = urlConfigs.find(c => c.url === url);
    if (config) return config;
    
    // 2. 域名匹配
    try {
        const urlObj = new URL(url);
        const domain = urlObj.hostname;
        config = urlConfigs.find(c => {
            try {
                const configUrlObj = new URL(c.url);
                return configUrlObj.hostname === domain;
            } catch (e) {
                return false;
            }
        });
        if (config) return config;
    } catch (e) {
        // URL解析失败，忽略
    }
    
    // 3. 如果没有找到，返回null，将使用最近使用的选择器
    return null;
}

// 启用保存配置按钮
function enableSaveConfigButton() {
    const saveBtn = document.getElementById('modal-save-config-btn');
    if (saveBtn) {
        saveBtn.disabled = false;
        saveBtn.style.opacity = '1';
        saveBtn.style.cursor = 'pointer';
    }
}

// 禁用保存配置按钮
function disableSaveConfigButton() {
    const saveBtn = document.getElementById('modal-save-config-btn');
    if (saveBtn) {
        saveBtn.disabled = true;
        saveBtn.style.opacity = '0.5';
        saveBtn.style.cursor = 'not-allowed';
    }
}

// 保存当前页面配置
function saveCurrentPageConfig() {
    const selector = document.getElementById('modal-selector-input').value.trim();
    const attribute = document.getElementById('modal-attribute-input').value.trim();
    const extractBoth = document.getElementById('modal-extract-both').checked;
    const currentUrl = window.location.href;
    
    if (!selector) {
        showModalMessage('请先输入jQuery选择器', 'error');
        return;
    }
    
    // 检查是否已存在相同URL的配置
    chrome.storage.local.get(['urlConfigs'], function(data) {
        const urlConfigs = data.urlConfigs || [];
        const existingIndex = urlConfigs.findIndex(config => config.url === currentUrl);
        
        const newConfig = {
            url: currentUrl,
            selector: selector,
            attribute: attribute,
            extractBoth: extractBoth,
            createdAt: new Date().toISOString()
        };
        
        if (existingIndex >= 0) {
            // 更新现有配置
            urlConfigs[existingIndex] = newConfig;
            showModalMessage(`已更新当前页面的配置`, 'success');
        } else {
            // 添加新配置
            urlConfigs.push(newConfig);
            showModalMessage(`已保存当前页面的配置`, 'success');
        }
        
        // 保存到存储
        chrome.storage.local.set({urlConfigs: urlConfigs});
    });
}

// 页面加载时检查扩展状态
chrome.storage.local.get(['extensionEnabled'], function(data) {
    isExtensionEnabled = data.extensionEnabled || false;
    if (isExtensionEnabled) {
        createFloatingH();
    }
});